package com.andy.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class BrushFilter implements GlobalFilter, Ordered {

    private Map<String,LinkedList<Long>> requestFlowsMap = new ConcurrentHashMap <>();

    @Value("${brushFilter.duration}")
    private Long PAST_TIME_DURATION;

    @Value("${brushFilter.count}")
    private Long PAST_TIME_COUNT;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String clientIp = request.getRemoteAddress().getHostString();

        if(!chkBrushFlow(clientIp)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "拦截暴刷!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    /**
     * 获取当前ip登录记录
     * @param ip
     * @return
     */
    private LinkedList<Long> getRequestFlow(String ip){
        //容器没有就新建
        if(!requestFlowsMap.containsKey(ip)){
            synchronized (requestFlowsMap){
                if(!requestFlowsMap.containsKey(ip)) {
                    LinkedList <Long> requestFlows = new LinkedList <Long>();
                    requestFlowsMap.put(ip, requestFlows);
                }
            }
        }

        return requestFlowsMap.get(ip);
    }

    /**
     * 删除过期
     * @param requestFlows
     */
    private void rmPastFlow(LinkedList<Long> requestFlows){
        long now = System.currentTimeMillis();
        synchronized (requestFlows){
            while(requestFlows.size()>0){
                Long duration = now-requestFlows.peek();
                if(duration>PAST_TIME_DURATION){
                    requestFlows.poll();
                }else{
                    break;
                }
            }
        }
    }

    /**
     * 校验是否暴刷
     * @param clientIp
     * @return
     */
    private boolean chkBrushFlow(String clientIp){
        LinkedList<Long> requestFlows = getRequestFlow(clientIp);
        synchronized (requestFlows){
            //把过期的删除
            rmPastFlow(requestFlows);
            //判断是否超数
            if(requestFlows.size()>=PAST_TIME_COUNT){
                return false;
            }

            return true;
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
